package org.zs.dao;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.zs.entity.User;


/**
 * 用户表
 *
 */
public class UserDAO extends BaseDAO<User> {
	
	private String tableName; 
	public UserDAO(){
		tableName = config.get("用户表");
	}
	
	@Override
	public User find(Serializable id) {
		String sql = "select * from "+tableName+" where userId = ?";
		PreparedStatement pt = getSqlPt(sql);
		int i = 1;
		setInt(id, pt, i++);
		ResultSet rs = result(pt);
		User u = null;
		if(rsNext(rs))
		{
			u = getEntityByRS(rs);
		}
		close(rs);
		close(pt);
		return u;
	}

	@Override
	public User add(User entity) {
		String sql = "insert into "+tableName+" values(0,?,?,?,?,?,?,?)";
		PreparedStatement pt = getSqlPt(sql);
		int i = 1;
		setString(entity.getLoginName(), pt, i++);
		setString(entity.getPassword(), pt, i++);
		setString(entity.getRemark(), pt, i++);
		setInt(entity.getSwin(), pt, i++);
		setInt(entity.getWwin(), pt, i++);
		setInt(entity.getSfall(), pt, i++);
		setInt(entity.getWfall(), pt, i++);
		entity.setUserId(resultForId(pt));
		close(pt);
		return entity;
	}

	@Override
	public boolean remove(Serializable id) {
		
		return false;
	}

	@Override
	public User update(User entity) {
		
		return null;
	}

	@Override
	public User getEntityByRS(ResultSet rs) {
		User u = new User();
		try {
			int userId = rs.getInt("userId");
			String loginName = rs.getString("loginName");
			String password = rs.getString("password");
			String remark = rs.getString("remark");
			int swin = rs.getInt("swin");
			int wwin = rs.getInt("wwin");
			int sfall = rs.getInt("sfall");
			int wfall = rs.getInt("wfall");
			u.setUserId(userId);
			u.setLoginName(loginName);
			u.setPassword(password);
			u.setRemark(remark);
			u.setSwin(swin);
			u.setSfall(sfall);
			u.setWwin(wwin);
			u.setWfall(wfall);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return u;
	}
	
	public User existsUser(User u)
	{
		String sql = "select * from "+tableName+" where loginName = ? and password = ?";
		PreparedStatement pt = getSqlPt(sql);
		int i =1;
		setString(u.getLoginName(), pt, i++);
		setString(u.getPassword(), pt, i++);
		ResultSet rs = result(pt);
		User user = null;
		if(rsNext(rs))
		{
			user = getEntityByRS(rs);
		}
		close(rs);
		close(pt);
		return user;
	}

	
}
